<template>
  <div class="app-container">
    <div class="header">
      <el-page-header @back="goBack"  />
      <div class="header-info">
        <el-tag type="info">最多可选择 {{ maxVolunteer }} 个志愿</el-tag>
      </div>
    </div>

    <div class="content-wrapper">
      <!-- 左侧队伍列表 (70%) -->
      <div class="left-panel">
        <TeamListPanel ref="teamListPanelRef" :deptId="deptId" :teacherId="teacherId" :selected-teams="selectedTeams" :max-volunteer="maxVolunteer" @select-team="handleSelectTeam" @unselect-team="handleUnselectTeam" @group-change="handleGroupChange" />
      </div>

      <!-- 右侧志愿表单 (30%) -->
      <div class="right-panel">
        <TeacherVolunteerPanel :selected-teams="selectedTeams" :submitting="submitting" :max-volunteer="maxVolunteer" @unselect-team="handleUnselectTeam" @move-up="handleMoveUp" @move-down="handleMoveDown" @submit="handleSubmit" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { getUserProfile } from '@/api/system/user'
import { addTeacherVolunteer, getTeacherVolunteer } from '@/api/teacherVolunteer'
import TeamListPanel from './components/TeamListPanel.vue'
import TeacherVolunteerPanel from './components/TeacherVolunteerPanel.vue'

const router = useRouter()
const { proxy } = getCurrentInstance()

// 组件引用
const teamListPanelRef = ref(null)

// 数据
const maxVolunteer = ref(0) // 最多可选择的志愿数量
const deptId = ref(null)
const teacherId = ref(null)
const selectedTeams = ref([])
const submitting = ref(false)
const userProfile = ref({})

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await getUserProfile()
    if (res && res.data) {
      userProfile.value = res.data.data
      deptId.value = userProfile.value?.dept?.deptId
      teacherId.value = userProfile.value?.teacher?.teacherId

    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    proxy.$modal.msgError('获取用户信息失败')
  }
}

// 处理分组变化
const handleGroupChange = async (groupInfo) => {
  // 清空已选择的志愿队伍
  selectedTeams.value = []

  if (groupInfo) {
    maxVolunteer.value = groupInfo.teacherMax

    // 获取该分组下已有的教师志愿
    await loadExistingVolunteers(groupInfo.groupId)
  } else {
    maxVolunteer.value = 0
  }
}

// 加载已有的志愿数据
const loadExistingVolunteers = async (groupId) => {
  if (!teacherId.value || !groupId) {
    console.warn('缺少必要参数，无法加载已有志愿', { teacherId: teacherId.value, groupId })
    return
  }

  try {
    const res = await getTeacherVolunteer(groupId, teacherId.value)
    console.log('获取已有志愿响应:', res)

    if (res && res.data && res.data) {
      const existingVolunteers = res.data

      // 如果返回的是数组且有数据
      if (Array.isArray(existingVolunteers) && existingVolunteers.length > 0) {
        console.log('原始志愿数据:', existingVolunteers)

        // 按照 sort 字段排序
        const sortedTeams = existingVolunteers.sort((a, b) => a.sort - b.sort)

        // 转换数据格式并加载到 selectedTeams
        selectedTeams.value = sortedTeams.map((item) => {
          // 确保 team 对象存在
          if (!item.team) {
            console.error('志愿数据缺少 team 对象:', item)
            return null
          }

          return {
            ...item.team, // 展开队伍信息（包括 teamId, teamName, summary, studentTeams 等）
            volunteerOrder: item.sort // 使用 sort 字段作为志愿顺序
          }
        }).filter(Boolean) // 过滤掉 null 值

        console.log('转换后的志愿数据:', selectedTeams.value)

        if (selectedTeams.value.length > 0) {
          proxy.$modal.msgSuccess(`已加载 ${selectedTeams.value.length} 个已选志愿`)
        }
      } else {
        console.log('暂无已选志愿')
      }
    }
  } catch (error) {
    console.error('加载已有志愿失败:', error)
    // 加载失败不影响用户继续选择，只提示警告
    if (error.response?.status !== 404) {
      proxy.$modal.msgWarning('加载已有志愿失败，请重新选择')
    }
  }
}

// 选择队伍
const handleSelectTeam = (team) => {
  if (selectedTeams.value.some(t => t.teamId === team.teamId)) {
    proxy.$modal.msgWarning('该队伍已被选择')
    return
  }

  if (selectedTeams.value.length >= maxVolunteer.value) {
    proxy.$modal.msgWarning(`最多只能选择${maxVolunteer.value}个志愿`)
    return
  }

  // 添加志愿顺序
  const newTeam = {
    ...team,
    volunteerOrder: selectedTeams.value.length + 1
  }
  selectedTeams.value.push(newTeam)
}

// 取消选择队伍
const handleUnselectTeam = (teamId) => {
  const index = selectedTeams.value.findIndex(t => t.teamId === teamId)
  if (index !== -1) {
    selectedTeams.value.splice(index, 1)
    // 重新排序
    selectedTeams.value.forEach((team, idx) => {
      team.volunteerOrder = idx + 1
    })
  }
}

// 上移
const handleMoveUp = (index) => {
  if (index > 0) {
    const temp = selectedTeams.value[index]
    selectedTeams.value[index] = selectedTeams.value[index - 1]
    selectedTeams.value[index - 1] = temp
    // 更新顺序
    selectedTeams.value.forEach((team, idx) => {
      team.volunteerOrder = idx + 1
    })
  }
}

// 下移
const handleMoveDown = (index) => {
  if (index < selectedTeams.value.length - 1) {
    const temp = selectedTeams.value[index]
    selectedTeams.value[index] = selectedTeams.value[index + 1]
    selectedTeams.value[index + 1] = temp
    // 更新顺序
    selectedTeams.value.forEach((team, idx) => {
      team.volunteerOrder = idx + 1
    })
  }
}

// 重置页面状态
const resetPageState = () => {
  // 清空志愿选择
  selectedTeams.value = []

  // 重置最大志愿数
  maxVolunteer.value = 0

  // 重置左侧筛选条件（年级、分组、队伍列表等）
  if (teamListPanelRef.value) {
    teamListPanelRef.value.resetQuery()
  }

  console.log('页面状态已重置: 志愿列表、最大志愿数、筛选条件均已清空')
}

// 提交志愿
const handleSubmit = async () => {
  if (selectedTeams.value.length === 0) {
    proxy.$modal.msgWarning('请至少选择一个志愿队伍')
    return
  }

  const teacherId = userProfile.value?.teacher?.teacherId
  if (!teacherId) {
    proxy.$modal.msgError('获取教师信息失败')
    return
  }

  submitting.value = true
  try {
    // 构造提交数据
    const submitData = {
      teacherId,
      groupId: selectedTeams.value[0].groupId,
      teams: selectedTeams.value.map(t => ({
        teamId: t.teamId,
        sort: t.volunteerOrder
      }))
    }
    await addTeacherVolunteer(submitData)
    proxy.$modal.msgSuccess('提交志愿成功')

    // 重置页面到初始状态
    resetPageState()

    console.log('已重置页面到初始状态')
  } catch (error) {
    console.error('提交志愿失败:', error)
    proxy.$modal.msgError(error.message || '提交志愿失败')
  } finally {
    submitting.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}

// 初始化
getUserInfo()
</script>

<style scoped lang="scss">
.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-info {
  display: flex;
  gap: 12px;
  align-items: center;
}

.content-wrapper {
  display: flex;
  height: calc(100vh - 164px);
  width: 100%;
  gap: 20px;
  align-items: flex-start;
}

.left-panel {
  width: 70%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.right-panel {
  width: 30%;
  height: 100%;
}
</style>
